package cn.acewill.yxd.yunxundian.ui.sign.Presenter;


import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.ChongFuKouFen;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.EditModel;
import cn.acewill.yxd.yunxundian.ui.sign.Contract.EditPresenter;

/**
 * Created by xxx on 2018/1/16.
 */

public class EditPresenterIml implements EditPresenter{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private EditModel loadView;
    private  ArrayList<RMain> rMains;
    private  ArrayList<RMain.TablesBean.Q1Bean> majorList;
    private  ArrayList<RMain.TablesBean.RowsBean.Q2Bean> minList;

    public EditPresenterIml(EditModel loadView){
        this.loadView = loadView;
    }
    @Override
    public void loadLocalData(final int schid) {
        if (loadView!=null){
            //加载数据
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Schedule schedule = null;
                    try {
                        schedule = db.selector(Schedule.class).where("ID", "=", schid).findFirst();
                        sType type = db.selector(sType.class).where("ID", "=", schedule.getSTypeID()).findFirst();
                        List<rJson> jsonList = db.selector(rJson.class).findAll();
                        rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
                        if (rmian==null){
                            loadView.loadRmainErro();
                            return;
                        }
                        String json = rmian.getjSon();
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<RMain>>() {
                        }.getType();
                        rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
                   /*大项集合*/
                        majorList = new ArrayList<>();
                        minList = new ArrayList<>();
                        List<RMain.TablesBean> TableList = rMains.get(0).getTables();
                        for (int i = 0; i < TableList.size(); i++) {
                            RMain.TablesBean tablesBean = TableList.get(i);
                            majorList.add(tablesBean.getQ1());
                        }
                        //获取全部的小项
                        if (majorList.size() > 0) {
//                    for (int k = 0;k<majorList.size();k++){
//                        List<RMain.TablesBean.RowsBean> rowlist=rMains.get(0).getTables().get(k).getRows();
//                        if (rowlist!=null&&rowlist.size()>0){
//                            for (int j =0;j<rowlist.size();j++){
//                                minList.add(rowlist.get(j).getQ2());
//                            }
//                        }
//                    }
                            //只获取当前第一个大项
                            List<RMain.TablesBean.RowsBean> rowlist = rMains.get(0).getTables().get(0).getRows();
                            if (rowlist != null && rowlist.size() > 0) {
                                for (int j = 0; j < rowlist.size(); j++) {
                                    minList.add(rowlist.get(j).getQ2());
                                }
                            }
                        }
                        Message msg = new Message();
                        msg.what = 0;
                        handler.sendMessage(msg);

                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==0){
                loadView.updateAdapter(rMains,majorList,minList);
            }
            return false;
        }
    });




    @Override
    public void loadMinListByPosition(int position) {
        if (loadView!=null&&majorList!=null){
            if (majorList.size()>0){
                minList = new ArrayList<>();
                List<RMain.TablesBean.RowsBean> rowlist=rMains.get(0).getTables().get(position).getRows();
                if (rowlist!=null&&rowlist.size()>0){
                        for (int j =0;j<rowlist.size();j++){
                            minList.add(rowlist.get(j).getQ2());
                        }
                }
            }
            loadView.refreshAdapterByPosition(rMains,minList);
        }
    }

    @Override
    public void searchMinItem(String str) {
        if (loadView!=null&&rMains!=null){
            List<RMain.TablesBean.RowsBean.Q2Bean> q2Beans = new ArrayList<>();
            List<RMain.TablesBean> tablesBeans = rMains.get(0).getTables();
            if (tablesBeans!=null && tablesBeans.size()>0){
                for (int i = 0; i<tablesBeans.size();i++){
                    List<RMain.TablesBean.RowsBean> rowsBeans = tablesBeans.get(i).getRows();
                    if (rowsBeans!=null&&rowsBeans.size()>0){
                        for (RMain.TablesBean.RowsBean row:rowsBeans){
                            if (row.getQ2().getReportRowName().contains(str))
                                 q2Beans.add(row.getQ2());
                        }
                    }
                }
            }
            loadView.searchDataByMinName(rMains,q2Beans);
        }
    }

    @Override
    public void loadRepeatLost(int schId) {
        HashMap<String,String> map = new HashMap<>();
        map.put("task","chongfukoufen");
        map.put("schid",schId+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] array = result.split("\\|");
                    if (array[0].equals("200")) {
                        //noJson
                        if (array[3].equals("noJson")){
                            return;
                        }
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<ChongFuKouFen>>() {
                        }.getType();

                        ArrayList<ChongFuKouFen> koufens = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                        loadView.setChongFuKouFen(koufens);
                    }
                }
                @Override
                public void onFailture() {

                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //返回headName
    public String getQ1ByRow(RMain.TablesBean.RowsBean.Q2Bean q2Bean){
        if (majorList!=null&&majorList.size()>0){
            for (RMain.TablesBean.Q1Bean q1:majorList){
                if (q1.getID() == q2Bean.getReportTableID()){
                    return q1.getReportTableName();
                }
            }
        }
        return "erro";
    }
    public String getPostionCount(RMain.TablesBean.RowsBean.Q2Bean q2Bean){
        int nowCount = 0;
        int aCount = 0;
        if (majorList!=null&&majorList.size()>0){
             aCount = majorList.size();
            for (int k = 0;k<aCount;k++){
                if (majorList.get(k).getID() == q2Bean.getReportTableID()){
                    nowCount = k+1;
                    break;
                }
            }
        }
        return nowCount+"/"+aCount;
    }
    //返回当前position的分组类型
    public int getTypeByPosition(int position){
        int count = 0;
        if (position == 0){ //第一个item
            return count;
        }else{
            for (int i = 0;i<position;i++){ //根据大项的id，找到对应的所有小项的数据
                RMain.TablesBean.Q1Bean q1Bean = majorList.get(i);
                for (RMain.TablesBean.RowsBean.Q2Bean q2Bean:minList){
                    if (q1Bean.getID() == q2Bean.getReportTableID()){
                        count++;
                    }
                }
            }
            return count;
        }
    }
}
